"use client"

import { useEffect, useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { ArrowLeftIcon, DownloadIcon, ShareIcon } from "lucide-react"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { type DetectionResult, getDetectionResult } from "@/lib/image-detection"

export function DetectionResults({ id }: { id: string }) {
  const [result, setResult] = useState<DetectionResult | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchResult = async () => {
      try {
        setLoading(true)
        // In a real app, you would fetch the result from your API
        const data = await getDetectionResult(id)
        setResult(data)
      } catch (error) {
        console.error("Failed to fetch result:", error)
      } finally {
        setLoading(false)
      }
    }

    fetchResult()
  }, [id])

  if (loading) {
    return <ResultsSkeleton />
  }

  if (!result) {
    return (
      <Card>
        <CardContent className="flex flex-col items-center justify-center p-6">
          <p className="text-lg font-medium">未找到结果</p>
          <p className="text-muted-foreground">无法找到该 ID 的检测结果</p>
          <Button asChild className="mt-4">
            <Link href="/">返回首页</Link>
          </Button>
        </CardContent>
      </Card>
    )
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <Button variant="outline" size="sm" asChild>
          <Link href="/">
            <ArrowLeftIcon className="mr-2 h-4 w-4" />
            返回
          </Link>
        </Button>
        <div className="flex flex-wrap gap-2">
          <Button variant="outline" size="sm">
            <ShareIcon className="mr-2 h-4 w-4" />
            分享
          </Button>
          <Button variant="outline" size="sm">
            <DownloadIcon className="mr-2 h-4 w-4" />
            下载结果
          </Button>
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        <Card>
          <CardContent className="p-4">
            <div className="relative aspect-square overflow-hidden rounded-md">
              <Image src={result.imageUrl || "/placeholder.svg"} alt="已检测的图像" fill className="object-contain" />
            </div>
          </CardContent>
        </Card>

        <div className="flex flex-col gap-4">
          <Tabs defaultValue="all">
            <TabsList>
              <TabsTrigger value="all">所有对象 ({result.objects.length})</TabsTrigger>
              <TabsTrigger value="people">
                人物 ({result.objects.filter((obj) => obj.type === "person").length})
              </TabsTrigger>
              <TabsTrigger value="objects">
                物品 ({result.objects.filter((obj) => obj.type === "object").length})
              </TabsTrigger>
              <TabsTrigger value="scenes">
                场景 ({result.objects.filter((obj) => obj.type === "scene").length})
              </TabsTrigger>
            </TabsList>

            <TabsContent value="all" className="mt-4">
              <ObjectList objects={result.objects} />
            </TabsContent>

            <TabsContent value="people" className="mt-4">
              <ObjectList objects={result.objects.filter((obj) => obj.type === "person")} />
            </TabsContent>

            <TabsContent value="objects" className="mt-4">
              <ObjectList objects={result.objects.filter((obj) => obj.type === "object")} />
            </TabsContent>

            <TabsContent value="scenes" className="mt-4">
              <ObjectList objects={result.objects.filter((obj) => obj.type === "scene")} />
            </TabsContent>
          </Tabs>

          <Card>
            <CardContent className="p-4">
              <h3 className="mb-2 font-medium">图像信息</h3>
              <div className="grid grid-cols-2 gap-2 text-sm">
                <div className="text-muted-foreground">上传时间</div>
                <div>{new Date(result.timestamp).toLocaleString()}</div>
                <div className="text-muted-foreground">文件大小</div>
                <div>{result.fileSize}</div>
                <div className="text-muted-foreground">分辨率</div>
                <div>{result.resolution}</div>
                <div className="text-muted-foreground">检测耗时</div>
                <div>{result.processingTime}秒</div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}

function ObjectList({ objects }: { objects: Array<{ id: string; name: string; confidence: number; type: string }> }) {
  if (objects.length === 0) {
    return <p className="text-muted-foreground">未检测到对象</p>
  }

  return (
    <div className="grid gap-2">
      {objects.map((object) => (
        <Card key={object.id}>
          <CardContent className="flex items-center justify-between p-3">
            <div className="flex items-center gap-2">
              <Badge variant="outline" className="capitalize">
                {object.type}
              </Badge>
              <span className="font-medium">{object.name}</span>
            </div>
            <Badge variant="secondary">{(object.confidence * 100).toFixed(0)}%</Badge>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}

function ResultsSkeleton() {
  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <Skeleton className="h-9 w-24" />
        <div className="flex gap-2">
          <Skeleton className="h-9 w-24" />
          <Skeleton className="h-9 w-24" />
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        <Skeleton className="aspect-square rounded-lg" />
        <div className="flex flex-col gap-4">
          <Skeleton className="h-10 w-full" />
          <div className="grid gap-2">
            {Array(5)
              .fill(0)
              .map((_, i) => (
                <Skeleton key={i} className="h-14 w-full" />
              ))}
          </div>
          <Skeleton className="h-40 w-full" />
        </div>
      </div>
    </div>
  )
}
